

package com.adtec.yxdemo.utils;

import java.util.HashMap;
import java.util.Map;

import com.adtec.yxdemo.mockLogin.entity.po.YxAccountInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

public class DataUtil {
    // 单例实例
    public static final DataUtil me = new DataUtil();
    // 日志对象
    public static final Log log = Log.getLog(DataUtil.class);


    /**
     * 获取支付订单跟踪数据
     * @param account
     * @param orderNo 订单编号
     * @return
     */
    public static String getPayTrack(YxAccountInfo account, String orderNo) {
        String logDesc = account.getAccountUsername() + "获取支付订单【" + orderNo + "】跟踪数据";
        String url = "http://trade.zgyxcgw.cn:8062/payDetail/toPayOrderTraceDialogList.html?payOrderCode=" + orderNo;

        HttpRequest request = HttpUtil.createGet(url).removeHeader("User-Agent").addHeaders(getHeaders(account));
        HttpResponse response = YxUtil.excute(request, logDesc, false);
        if (response == null || response.getStatus() != 200) {
            log.warn(logDesc + "失败响应:" + response);
            return null;
        }
        Document doc = Jsoup.parse(response.body());
        Elements eles1 = doc.select(".formspan1");
        Elements eles2 = doc.select(".formspan2");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < eles1.size(); i++) {
            sb.append("\n").append(eles1.get(i).text());
            sb.append("\n").append(eles2.get(i).text());
        }
        log.info(sb.toString());
        return  sb.toString();
    }
    /**
     * 获取支付订单详情
     * @param account
     * @param orderNo 订单编号
     * @return
     */
    public static String getOrderDetail1(YxAccountInfo account, String orderNo) {
        String logDesc = account.getAccountUsername() + "获取支付订单【" + orderNo + "】详情1";
        String url = "http://trade.zgyxcgw.cn:8062/payOrder/toPayOrderDetail.html?payOrderCode=" + orderNo;
        HttpRequest request = HttpUtil.createGet(url).removeHeader("User-Agent").addHeaders(getHeaders(account));
        HttpResponse response = YxUtil.excute(request, logDesc, false);
        if (response == null || response.getStatus() != 200) {
            log.warn(logDesc + "失败响应:" + response);
            return null;
        }
        String body = response.body();
        return body;
    }
    /**
     * 获取支付订单详情
     * @param account
     * @param orderNo 订单编号
     * @return
     */
    public static JSONArray getOrderDetails(YxAccountInfo account, String orderNo) {
        String logDesc = account.getAccountUsername() + "获取支付订单【" + orderNo + "】详情";
        String url = "http://trade.zgyxcgw.cn:8062/payOrder/getPayDetailChoosed.html";
        String body = "payOrderCode=%s&payStatus=-1&_search=false&nd=%d";
        body = String.format(body, orderNo, System.currentTimeMillis()) + "&rows=100&page=1&sidx=t.storage_date%2Ct.storage_tag&sord=";

        HttpRequest request = HttpUtil.createPost(url).removeHeader("User-Agent").addHeaders(getHeaders(account)).body(body);
        HttpResponse response = YxUtil.excute(request, logDesc, false);
        if (response == null || response.getStatus() != 200 || !JSONUtil.isJson(response.body())) {
            log.warn(logDesc + "失败响应:" + response);
            return null;
        }
        JSONObject result = JSONUtil.parseObj(response.body());
        JSONArray list = result.getJSONArray("rows");
        return list;
    }

    /**
     * 获取支付订单列表
     * @param account
     * @return
     */
    public static JSONArray getPayInfoList(YxAccountInfo account) {
        int page = 1;
        int rows = 100;
        JSONArray list = new JSONArray();
        while (getOrderList(account, list, page, rows)) {
            page++;
            if(page>1){
                break;
            }else {
                continue;
            }
        }
        log.info("获取支付订单列表条数：" + list.size());
//        FileUtil.writeString(list.toString(), "D:\\test.txt", "UTF-8");
        return list;
    }

    /**
     * 获取支付订单列表
     * @param account
     * @param list 支付订单列表
     * @param page 页号，从1开始
     * @param rows 每页条数
     * @return 是否有下一页，true-有下一页
     */
    private static boolean getOrderList(YxAccountInfo account, JSONArray list, int page, int rows) {
        String logDesc = account.getAccountUsername() + "获取支付订单列表第【" + page + "】页";
        String url = "http://trade.zgyxcgw.cn:8062/payOrder/getDistributionInfos.html";
        String body = "_search=false&nd=%d&rows=%d&page=%d&sidx=t.add_time&sord=desc&payOrgName=&payOrderCode=&payStatus=&startTime=&endTime=&payIsEnd=&warehouseAmountStart=&warehouseAmountEnd=&startAmount=&endAmount=&returnAmountStart=&returnAmountEnd=&addUserName=";
        body = String.format(body, System.currentTimeMillis(), rows, page);

        HttpRequest request = HttpUtil.createPost(url).removeHeader("User-Agent").addHeaders(getHeaders(account)).body(body);
        HttpResponse response = YxUtil.excute(request, logDesc, false);
        if (response == null || response.getStatus() != 200 || !JSONUtil.isJson(response.body())) {
            log.warn(logDesc + "失败响应:" + response);
            return false;
        }
        JSONObject result = JSONUtil.parseObj(response.body());
        list.addAll(result.getJSONArray("rows"));

        return result.getInt("total") > page;
    }
    /**
     * 获取请求头信息
     * @param seller
     * @return
     */
    private static Map<String, String> getHeaders(YxAccountInfo seller) {
        HttpRequest.closeCookie();
        Map<String, String> headers = new HashMap<>();
        if (seller != null && StrKit.notBlank(seller.getCookie())) {
            headers.put("Cookie", seller.getCookie());
        }
        String cookie = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36";
        headers.put("User-Agent", cookie);
        return headers;
    }

    /**
     * 字符串处理
     */
    public static String getRightStr(String s) {
        if (s != null) {
            String str = s.trim();
            if (str.length() == 0) {
                return null;
            } else {
                return str;
            }
        }
        return null;
    }
}
